package com.learn.training.multithread.chapter6.minchapter5.demo1;

import java.util.ArrayList;
import java.util.List;

public class Demo1 {

    public static void main(String[] args) throws InterruptedException {

        TaskQueue queue = new TaskQueue();
        List<Thread> ts = new ArrayList<Thread>();

        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(){
                public void run(){
                    while (true) {
                        try {
                            String s = queue.getTask();
                            System.out.println(Thread.currentThread().getName() + "  execute task : " + s + "   " + Thread.currentThread().getState());
                        } catch (InterruptedException e) {
                            return;
                        }
                    }
                }
            };
            thread.start();
            ts.add(thread);
        }

        Thread t = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                String s = "t-" + Math.random();
                System.out.println(Thread.currentThread().getName() + "  add task : " + s);
                queue.addTask(s);
                try {
                    Thread.sleep(100);
                }catch (InterruptedException e){}
            }
        });

        t.start();
        t.join();

        Thread.sleep(100);
        for (Thread thread : ts) {
            thread.interrupt();
        }


    }
}
